<?php

namespace App\Console\Commands;

use App\Models\Circle;
use App\Models\Subscribe;
use App\Services\PublishTemplateService;
use Illuminate\Console\Command;

class PushActivityNoticeCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'push-activity-notice';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        \Log::info('-----------start-push-notice-----------------------------');
        Circle::where('is_activity', 1)->where('is_push_start_notice', 0)->where('activity_start_at', '>=', date('Y-m-d H:i:s'))
            ->chunkById(10, function ($activity_list) {
            foreach ($activity_list as $activity_item) {
                Subscribe::where('type', Subscribe::TYPE_ACTIVITY_START)->withCertain('user', ['openid'])->chunkById(50, function ($list) use($activity_item) {
                    foreach ($list as $item) {
                        $service = new PublishTemplateService();
                        $service->activity_start($item->user->openid, $activity_item->title, $activity_item->id,$activity_item->activity_start_at, $activity_item->activity_end_at);
                        $item->delete();
                    }
                });
                $activity_list->is_push_start_notice = 1;
                $activity_item->save();
            }
        });
        \Log::info('-----------end-push-notice-----------------------------');
    }
}
